package cn.unknowpupil.init.utils;


import cn.unknowpupil.init.domain.dto.LoginUser;
import cn.unknowpupil.init.exceptions.HealthException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * Created at 2020/10/19 by w10g <br>
 * Initialize SecurityUtils ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
public class SecurityUtils {
    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            Authentication principal = getAuthentication();
            if (Objects.isNull(principal)) {
                return null;
            } else {
                return (LoginUser) principal.getPrincipal();
            }
        } catch (Exception e) {
            throw new HealthException(e.getMessage());
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {

        return userId != null && 1L == userId;
    }

    public static boolean isSuperAdmin(Long pId) {

        return pId != null && 0L == pId;
    }
}
